import { el } from 'element-plus/es/locales.mjs';
import request from './request'

interface ChatMessageDto {
    modelType: string,
    message: string,
    conversationId: string
}

interface ChatMessageVo {
    conversationId: string,
    message: string,
    messageType: string,
    endFlag: Boolean,
    startFlag: Boolean,
    isThink: Boolean
}

export function chatStream(
    chatMessageDto: ChatMessageDto,
    onOpen: (text: string) => void,
    onMessage: (text: string) => void,
    onThink: (text: string) => void,
    onComplete?: () => void,
    onError?: (err: any) => void

): EventSource {
    const params = encodeURIComponent(JSON.stringify(chatMessageDto));
    const eventSource = new EventSource(`/api/llm/chat/chatStream?sseData=${params}`);

    eventSource.onmessage = function (event) {
        let chatMessageVo: ChatMessageVo = JSON.parse(event.data)
        if (chatMessageVo.startFlag) {
            onOpen(chatMessageVo.conversationId)
        } else if (chatMessageVo.endFlag) {
            onComplete
        } else if (chatMessageVo.isThink) {
            onThink(chatMessageVo.message)
        }
        else {
            onMessage(chatMessageVo.message)
        }
    };


    eventSource.onerror = function (err) {
        eventSource.close(); // 可选：出错后关闭连接
    };

    eventSource.onopen = function () {

    };

    return eventSource; // 可返回用于外部调用 eventSource.close()

}

export function newConversation() {
    return request({
        url: '/llm/chat/newConversation',
        method: 'post',
    })
}


export function conversationList() {
    return request({
        url: '/llm/chat/conversationList',
        method: 'post',
    })
}


export function getChatConversation(conversationId: string) {
    return request({
        url: '/llm/chat/getChatConversation',
        method: 'get',
        params: {
            conversationId: conversationId
        }
    })
}




